package JurisPro.modelo.banco;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;


public class Conexao {

	private static Conexao singleton = null;
	
	public static Conexao getInstance() {
		if(singleton == null)
			singleton = new Conexao();
		return Conexao.singleton;
	}

	private Conexao() {
		super();
		this.init("com.microsoft.sqlserver.jdbc.SQLServerDriver", "jdbc:sqlserver://localhost:1433;databaseName=jurispro","sa","senha");
	}
	
	public void init(String driver, String url, String usuario, String senha) {
		try {
			Class.forName(driver);
			this.conexao = DriverManager.getConnection(url, usuario, senha);
		} catch (ClassNotFoundException e) {
			System.out.println("Classe nao encontrada!");
			e.printStackTrace();
		} catch (SQLException e) {
			System.out.println("Error no SQL!");
			e.printStackTrace();
		}
	}
	
	private Connection conexao;
	
	public Statement getState(){
		Statement state = null;
		try {
			state = conexao.createStatement();
			return state;
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("Error no SQL!");
		}
		return state;	
	}

	public PreparedStatement getPrepState(String sql){
		PreparedStatement state = null;
		try {
			state = conexao.prepareStatement(sql);			
			return state;
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("Error no SQL!");
		}
		return state;	
	}

	public ResultSet selectComand(String sql){
		ResultSet rs = null;
		try {	
			Statement state = this.getState(); 
			rs = state.executeQuery(sql);
			this.getState().close();
			return rs;
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("ERROR SQL RS!");
		}
		return rs;
	}

	public int updateComand(String sql){
		int numRows = -1;
		try {		
			Statement state = this.getState();
			numRows = state.executeUpdate(sql);
			this.getState().close();
			
			return numRows;		
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return numRows;
	}
	
}

